package com.dw.gui.panel.diagnosis;

import com.dw.dao.diagnosis.DiagnosisDocumentDao;
import com.dw.dao.other.AppointmentDao;
import com.dw.dao.user.PatientDao;
import com.dw.model.diagnosis.DiagnosisDocument;
import com.dw.model.other.Appointment;
import com.dw.model.user.Doctor;
import com.dw.model.record.MedicalRecord;
import com.dw.util.UIUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.SQLException;

public class DiagnosisDocumentPanel extends JPanel {
    private JTextArea taDiagnosis;
    private JTextArea taTreatment;

    private final Doctor doctor;
    private Appointment appointment;

    private final JTextField tfAppointmentId = UIUtil.createTextField();
    private final JTextField taPatientName = UIUtil.createTextField();

    private final AppointmentDao appointmentDao = new AppointmentDao();
    private final PatientDao patientDao = new PatientDao();

    public DiagnosisDocumentPanel(Doctor doctor) {
        this.doctor = doctor;
        initUI();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);

        // 标题面板（顶部）
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        titlePanel.setBackground(Color.WHITE);
        titlePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        titlePanel.add(UIUtil.createTitleLabel("下诊断书"));

        // 主内容面板（使用GridBagLayout）
        JPanel contentPanel = new JPanel(new GridBagLayout());
        contentPanel.setBackground(Color.WHITE);
        contentPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        gbc.gridx = 0;
        gbc.gridy = 0;
        contentPanel.add(UIUtil.createLabel("会诊ID："), gbc);
        gbc.gridx = 1;
        tfAppointmentId.addActionListener(e -> loadAppointment()); // 回车触发
        tfAppointmentId.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                loadAppointment(); // 失去焦点时触发
            }
        });
        tfAppointmentId.setColumns(10);
        contentPanel.add(tfAppointmentId, gbc);

        // 第一行：患者信息
        gbc.gridx = 0;
        gbc.gridy = 1;
        contentPanel.add(UIUtil.createLabel("患者姓名："), gbc);

        gbc.gridx = 1;
        taPatientName.setColumns(10);
        contentPanel.add(taPatientName, gbc);

        // 第二行：诊断结论
        gbc.gridx = 0;
        gbc.gridy = 2;
        contentPanel.add(UIUtil.createLabel("诊断结论："), gbc);

        gbc.gridx = 1;
        taDiagnosis = UIUtil.createTextArea(3, 30);
        contentPanel.add(new JScrollPane(taDiagnosis), gbc);

        // 第三行：治疗方案
        gbc.gridx = 0;
        gbc.gridy = 3;
        contentPanel.add(UIUtil.createLabel("治疗方案："), gbc);

        gbc.gridx = 1;
        taTreatment = UIUtil.createTextArea(3, 30);
        contentPanel.add(new JScrollPane(taTreatment), gbc);

        // 第五行：保存按钮
        gbc.gridx = 1;
        gbc.gridy = 4;
        gbc.anchor = GridBagConstraints.EAST;
        JButton btnSave = UIUtil.createButton("签发诊断书");
        btnSave.addActionListener(e -> saveDocument());
        contentPanel.add(btnSave, gbc);

        // 组装主界面
        add(titlePanel, BorderLayout.NORTH);
        add(contentPanel, BorderLayout.CENTER);
    }

    private void loadAppointment() {
        String input = tfAppointmentId.getText().trim();
        if (input.isEmpty()) return;

        new SwingWorker<Appointment, Void>() {
            @Override
            protected Appointment doInBackground() throws Exception {
                int appointmentId = Integer.parseInt(input);
                return appointmentDao.findById(appointmentId);
            }

            @Override
            protected void done() {
                try {
                    appointment = get();
                    if (appointment != null) {
                        taPatientName.setText(patientDao.findById(appointment.getPatientId()).getName());
                    } else {
                        UIUtil.showError(DiagnosisDocumentPanel.this, "未找到对应的会诊记录", "数据错误");
                    }
                } catch (NumberFormatException e) {
                    UIUtil.showError(DiagnosisDocumentPanel.this, "请输入有效的数字ID", "输入错误");
                } catch (Exception e) {
                    UIUtil.showError(DiagnosisDocumentPanel.this, "数据加载失败：" + e.getMessage(), "系统错误");
                }
            }
        }.execute();
    }


    private void saveDocument() {
        if (taDiagnosis.getText().trim().isEmpty()) {
            UIUtil.showError(this, "诊断结论不能为空", "输入错误");
            return;
        }

        try {
            DiagnosisDocument doc = new DiagnosisDocument();
            doc.setAppointmentId(appointment.getId());
            doc.setPatientId(appointment.getPatientId());
            doc.setDoctorId(doctor.getId());
            doc.setPatientId(appointment.getPatientId());
            doc.setDiagnosis(taDiagnosis.getText());
            doc.setTreatment(taTreatment.getText());

            new DiagnosisDocumentDao().create(doc);
            UIUtil.showInfo(this, "诊断书签发成功", "操作成功");
            clearForm();
        } catch (SQLException ex) {
            UIUtil.showError(this, "保存失败：" + ex.getMessage(), "数据库错误");
        }
    }

    private void clearForm() {
        taDiagnosis.setText("");
        taTreatment.setText("");
    }
}